﻿using System.IO;
using System.Xml.Serialization;

namespace Nexus.IPConfiguration.Management.Wrappers
{
    /// <summary>
    /// Base for wrapper classes
    /// </summary>
    public class WrapperBase
    {
        #region static methods
        /// <summary>
        /// Creates instace from xml string
        /// </summary>
        /// <typeparam name="T">Type of the object to deserialize</typeparam>
        /// <param name="xml">string containing serialized object</param>
        /// <returns>Deserialized object</returns>
        public static T CreateFromXmlString<T>(string xml)
        {
            T obj;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (StringReader stringReader = new StringReader(xml))
            {
                obj = (T)xmlSerializer.Deserialize(stringReader);
            }
            return obj;
        }
        #endregion

        #region overriden methods
        /// <summary>
        /// Serializes object and returns its representation as xml string
        /// </summary>
        /// <returns>Xml string</returns>
        public override string ToString()
        {
            string xml;
            XmlSerializer xmlSerializer = new XmlSerializer(GetType());
            using (StringWriter stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, this);
                xml = stringWriter.ToString();
            }
            return xml;
        }
        #endregion
    }
}
